<?php
/**
 * 注释不留名,代码随便用
 */

namespace app\common\library\basicadmin\logic;

use app\common\controller\BasicAdmin;
use app\common\library\basicadmin\Logic;

/**
 * 通用删除管理器
 * Class Delete
 * @package library\logic
 */
class Delete extends Logic
{
    /**
     * 表单额外更新条件
     * @var array
     */
    protected $where;
    /**
     * 数据对象主键名称
     * @var string
     */
    protected $pkField;
    /**
     * 数据对象主键值
     * @var string
     */
    protected $pkValue;

    /**
     * Delete constructor.
     * @param string|\think\Model $model
     * @param string $pkField 数据对象主键
     * @param array $where 额外更新条件
     */
    public function __construct($model, $pkField = '', $where = [])
    {
        parent::__construct();
        $this->where = $where;
        $this->model = $model;
        $this->pkField = empty($pkField) ? $this->model->getPk() : $pkField;
        $this->pkValue = $this->request->post($this->pkField, null);

    }

    /**
     * @param BasicAdmin $controller
     * @return mixed|null
     * @throws \Exception
     */
    public function init(BasicAdmin $controller)
    {
        $this->controller = $controller;


        // 主键限制处理
        if (!isset($this->where[$this->pkField]) && is_string($this->pkValue)) {
            $this->where[] = [$this->pkField, 'IN', $this->pkValue];
        }

        // 前置回调处理
        if (false === $this->controller->callback('_delete_filter', $this->model, $this->where)) {
            return null;
        }
        // 执行删除操作
        $list = $this->model->where($this->where)->all();
        foreach($list as $item){
            $item->delete();
        }
        // 结果回调处理
        if (false === $this->controller->callback('_delete_result', $result,  $this->where)) {
            return $result;
        }
        // 回复前端结果
        if ($result !== false) {
            $this->controller->success(lang('Successful data deletion'), '');
        } else {
            $this->controller->error(lang('Data deletion failed. Please try again later'));
        }
    }

}